package com.demo.admin.executor.service.impl;

import com.demo.admin.executor.entity.TmCustomer;
import com.demo.admin.executor.mapper.CustomerMapper;
import com.demo.admin.executor.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: CustomerServiceImpl
 * @Description:
 * @Author: Liu ZiQi
 * @create: 2020/12/15 15:12
 **/
@Service
@Slf4j
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Value("${job.clean.customer.expire.time}")
    private Integer expireTime;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cleanCustomer() throws Exception {
        // 筛选未激活的用户
        List<TmCustomer> tmCustomers = customerMapper.queryCleanCustomer();
        if (ObjectUtils.isEmpty(tmCustomers)) {
            return;
        }
        // 筛选未激活时间超过指定时间的用户
        List<Long> cleanCustomerIds = tmCustomers.stream()
                .filter(customer -> this.isClean(customer.getUpdateTime()))
                .map(TmCustomer::getId)
                .collect(Collectors.toList());
        log.error("{}", cleanCustomerIds);
        if (ObjectUtils.isEmpty(cleanCustomerIds)) {
            return;
        }
        // 处理这些超过指定时间未激活的用户
        if (cleanCustomerIds.size() != customerMapper.doCleanCustomer(cleanCustomerIds)) {
            throw new Exception("clean error");
        }
    }

    /**
     * 使用java8推荐的LocalDateTime进行日期时间的处理
     * @param updateTime
     * @return
     */
    private Boolean isClean(Date updateTime) {
        if (ObjectUtils.isEmpty(updateTime)) {
            return false;
        }
        return LocalDateTime.now().minus(expireTime, ChronoUnit.DAYS)
                .isAfter(
                        // Date -> LocalDateTime
                        LocalDateTime.ofInstant(updateTime.toInstant(), ZoneId.systemDefault())
                );
    }
}
